package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlcoal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmNewsService wmNewsService;
    /**
     * 图片上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if(multipartFile==null||multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        上传图片到minio中
//        String fileName = UUID.randomUUID().toString().replace("-", "");
        String fileName = UUID.randomUUID().toString();
//        aa.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId=null;
        try {
            fileId=fileStorageService.uploadImgFile("",fileName+substring,multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        将数据保存在数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(fileId);
        wmMaterial.setType((short)0);

        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }
    /**
     * 素材列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
//        校验参数
        if(StringUtils.isEmpty(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> lqw = new LambdaQueryWrapper<>();
//        判断是否珍藏
        if(dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            lqw.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
//        按照用户查询,时间排序
        lqw.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId()).orderByDesc(WmMaterial::getCreatedTime);
        page= page(page, lqw);

        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 图片删除
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Integer id) {
        if(id==null){
            return ResponseResult.errorResult(501,"参数失效");
        }
        WmMaterial byId = getById(id);
        if(StringUtils.isEmpty(byId)){
            return ResponseResult.errorResult(501,"参数失效");
        }
        LambdaQueryWrapper<WmNewsMaterial> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WmNewsMaterial::getMaterialId,id);
        WmNewsMaterial wmNewsMaterial = wmNewsMaterialMapper.selectOne(lqw);
        if(StringUtils.isEmpty(wmNewsMaterial)){
            wmMaterialMapper.deleteById(id);
            return ResponseResult.okResult(200,"操作成功");
        }
        LambdaQueryWrapper<WmNews> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(WmNews::getId,wmNewsMaterial.getNewsId());
        WmNews one = wmNewsService.getOne(lqw1);
        if(one.getStatus()==9){
            return ResponseResult.errorResult(501,"文件删除失败");
        }
        if(one.getStatus()==1){
            one.setImages("");
            wmNewsService.updateById(one);
            wmMaterialMapper.deleteById(id);
            return ResponseResult.okResult(200,"文件删除成功");
        }
        if(one.getStatus()>0&&one.getStatus()<9){
            return ResponseResult.errorResult(501,"文件删除失败");
        }
       return  ResponseResult.errorResult(501,"文件删除失败");
    }

    /**
     * 收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectById(Integer id) {
        if(id==null){
            return ResponseResult.errorResult(501,"参数失效");
        }
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if(StringUtils.isEmpty(wmMaterial)){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        wmMaterial.setIsCollection((short)1);
        wmMaterialMapper.updateById(wmMaterial);
        return ResponseResult.okResult(200,"操作成功");
    }

    @Override
    public ResponseResult collectById1(Integer id) {
        if(id==null){
            return ResponseResult.errorResult(501,"参数失效");
        }
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if(StringUtils.isEmpty(wmMaterial)){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        wmMaterial.setIsCollection((short)0);
        wmMaterialMapper.updateById(wmMaterial);
        return ResponseResult.okResult(200,"操作成功");

    }
}
